package Centralisateur.CentralisateurImplementation;

import java.util.ArrayList;
import java.io.*;
import Centralisateur.*;

public class LogFileController
{
	/** Name of the file containing the indexes locating the logs in the data file. */
	private final String INDEX_FILE_NAME = "Log.index";
	/** Name of the file containing the log data. */
	private final String DATA_FILE_NAME = "Log.data";
	/** Access to data file. */
	private PrintWriter _dataWriter;
	/** Log indexes. */
	private ArrayList<LogIndex> _indexes;
	/** hold the offset into the data file. */
	private int _lastOffset;

	/** Open the index file (create it if it does not exist). */
	public LogFileController()
	{
		// TODO : open existing file

		_indexes = new ArrayList<LogIndex>();
		_lastOffset = 0;

		try
		{
			_dataWriter = new PrintWriter(DATA_FILE_NAME);
		}
		catch (Exception exception)
		{
			throw new RuntimeException(exception.getMessage());
		}
	}

	/** Add a log to the centralized file. */
	public void addLog(Log log)
	{
		// Check logical time : if it is the same than another yet existing log, reject the new log as bad
		// TODO
		
		if (log.contenu != null)
		{
			// Add index for this log
			int dataLength = log.contenu.length();
			LogIndex logIndex = new LogIndex(log.dateLogique, _lastOffset, dataLength);
			_lastOffset += dataLength;

			// Add log content to data file
			_dataWriter.write(log.contenu);
		}
	}

	/** Close the log files. */
	public void close()
	{
		// Write indexes to file
		try
		{
			PrintWriter indexWriter = new PrintWriter(INDEX_FILE_NAME);

			int indexesCount = _indexes.size();
			for (int i = 0; i < indexesCount; i++)
			{
				LogIndex logIndex = _indexes.get(i);
				indexWriter.print(logIndex.getLogicalTime());
				indexWriter.print(logIndex.getOffset());
				indexWriter.print(logIndex.getLength());
			}

			indexWriter.close();
			_dataWriter.close();
		}
		catch (Exception exception)
		{
			throw new RuntimeException(exception.getMessage());
		}		
	}
}